package com.ruoyi.framework.websocket;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;

/**
 * PortalHandshakeInterceptor TODO
 *
 * @author augustqin
 * @Date 2025/2/18 16:21
 */
@Component
public class PortalHandshakeInterceptor implements HandshakeInterceptor {

    private final Logger logger = LoggerFactory.getLogger(PortalHandshakeInterceptor.class);


    /**
     * 初次握手访问前
     * @param request
     * @param serverHttpResponse
     * @param webSocketHandler
     * @param map
     * @return
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) {
        logger.info("HandshakeInterceptor beforeHandshake start...");
        if (request instanceof ServletServerHttpRequest) {
            HttpServletRequest req = ((ServletServerHttpRequest) request).getServletRequest();
            String authorization = req.getHeader("Sec-WebSocket-Protocol");
            logger.info("authorization = {}", authorization);
//            if (Objects.isNull(userClient)){
//                userClient = (UserClient) SpringContextUtil.getBean("userClient");
//            }
//            TokenVO tokenVO = userClient.checkToken(authorization, authorization);
//            Long userId = tokenVO.getUserId();
//            logger.info("userId = {}, tokenVO = {}", userId, tokenVO);
//            if (Objects.isNull(userId)){
//                serverHttpResponse.setStatusCode(HttpStatus.FORBIDDEN);
//                logger.info("【beforeHandshake】 authorization Parse failure. authorization = {}", authorization);
//                return false;
//            }
            //存入数据，方便在hander中获取，这里只是在方便在webSocket中存储了数据，并不是在正常的httpSession中存储，想要在平时使用的session中获得这里的数据，需要使用session 来存储一下
//            map.put(MagicCode.WEBSOCKET_USER_ID, userId);
//            map.put(MagicCode.WEBSOCKET_CREATED, System.currentTimeMillis());
//            map.put(MagicCode.TOKEN, authorization);
//            map.put(HttpSessionHandshakeInterceptor.HTTP_SESSION_ID_ATTR_NAME, req.getSession().getId());
//            logger.info("【beforeHandshake】 WEBSOCKET_INFO_MAP: {}", map);
        }
        logger.info("HandshakeInterceptor beforeHandshake end...");
        return true;
    }

    /**
     * 初次握手访问后，将前端自定义协议头Sec-WebSocket-Protocol原封不动返回回去，否则会报错
     * @param request
     * @param serverHttpResponse
     * @param webSocketHandler
     * @param e
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {
        logger.info("HandshakeInterceptor afterHandshake start...");
        HttpServletRequest httpRequest = ((ServletServerHttpRequest) request).getServletRequest();
        HttpServletResponse httpResponse = ((ServletServerHttpResponse) serverHttpResponse).getServletResponse();
        if (StringUtils.isNotEmpty(httpRequest.getHeader("Sec-WebSocket-Protocol"))) {
            httpResponse.addHeader("Sec-WebSocket-Protocol", httpRequest.getHeader("Sec-WebSocket-Protocol"));
        }
        logger.info("HandshakeInterceptor afterHandshake end...");
    }

}
